<?php
namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\Request;
use think\facade\View;
use app\validate\CheckUser;
use app\validate\CheckPassword;
use think\exception\ValidateException;



// 账户管理
class User extends BaseController
{
    public function index()
    {
        return View::fetch();
    }

    public function load(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $get = $request->get();

        $where = [];
        if (isset($get['admin_name'])) {
            if (!empty($get['admin_name'])) {
                $where[] = ['a.givenname|a.surname', 'like','%'.$get['admin_name'].'%'];
            }
        }

        $where[] = ['a.type', '=', 1];

        $total = Db::table('o_admin_user')
            ->alias('a')
            ->join('o_admin_role b', 'b.id=a.role_id')
            ->where($where)
            ->count();

        $data = Db::table('o_admin_user')
            ->alias('a')
            ->join('o_admin_role b', 'b.id=a.role_id')
            ->where($where)
            ->field('a.id, a.givenname, a.surname, a.email, a.role_id, a.status, a.add_time, b.rolename as role_name')
            ->page($get['page'], $get['limit'])
            ->select();

        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $data
        );
        return json($data);
    }


    public function add()
    {
        if(!check_jurisdiction1(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $role = Db::name('admin_role')
            ->where('type', 2)
            ->field('id, rolename as name')
            ->select();
        View::assign('role', $role);
        return View::fetch();
    }


    public function save(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();
        $post = remove_xss($post);

        // 验证
        try {

            validate(CheckUser::class)->check($post);

        } catch (ValidateException $e) {

            return $this->outputAjax($e->getError());
        }


        Db::startTrans();
        try {
            $insert = array(
                'givenname' => $post['givenname'],
                'role_id' => $post['role_id'],
                'surname' => $post['surname'],
                'email' => strtoupper($post['email']),
                'status' => 2,
                'add_time' => time(),
            );
            $getId = Db::table('o_admin_user')->insertGetId($insert);
            if (!$getId) {
                Db::rollback();
                return $this->outputAjax('操作失败！');
            }
            Db::commit();
            return $this->outputAjax('操作成功！',0);

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->outputAjax($e->getMessage());
        }
    }

    public function edit(Request $request)
    {
        if(!check_jurisdiction1(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $id = $request->get('id');

        $inf = Db::name('admin_user')
            ->where(array('id' => $id))
            ->field('id, givenname, surname, email, role_id')
            ->find();
        View::assign('inf', $inf);

        $role = Db::name('admin_role')->where('type', 2)->field('id, rolename as name')->select();
        View::assign('role', $role);

        return View::fetch();
    }


    public function modify(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();
        $post = remove_xss($post);

        // 验证
        try {

            validate(CheckUser::class)->check($post);

        } catch (ValidateException $e) {

            return $this->outputAjax($e->getError());
        }

        Db::startTrans();
        try {
            $update = array(
                'id' => $post['id'],
                'givenname' => $post['givenname'],
                'surname' => $post['surname'],
                'role_id' => $post['role_id'],
                'email' => strtoupper($post['email']),
            );

            if (!Db::table('o_admin_user')->update($update)) {
                Db::rollback();
                return $this->outputAjax('操作失败！');
            }
            Db::commit();
            return $this->outputAjax('操作成功！',0);

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->outputAjax($e->getMessage());
        }
    }

    public function toggle(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->post('id');
        if (!$id) {
            return $this->outputAjax();
        }

        try {
            $inf = Db::name('admin_user')->find($id);

            if (empty($inf)) {
                return $this->outputAjax('参数错误！');
            }

            if (!in_array($inf['status'], array(1, 2))) {
                return $this->outputAjax('参数错误[1]！');
            }

            $status = $inf['status'] == 1 ? 2 : 1;

            $update = array(
                'id' => $id,
                'status' => $status,
            );
            if(!Db::name('admin_user')->update($update)) {
                return $this->outputAjax('操作失败！');
            }

            return $this->outputAjax('操作成功！',0);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }

    }


    public function delete(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->post('id');
        if(!$id){
            return $this->outputAjax('参数不足！');
        }
        try {
            $result = Db::name('admin_user')->where('id','=',$id)->delete();

            if(!$result){
                return $this->outputAjax('操作失败！');
            }
            return $this->outputAjax('操作成功！',0);

        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    public function password()
    {
        return View::fetch();
    }

    public function modifyPassword(Request $request)
    {

        $post = $request->post();
        // 验证
        try {

            validate(CheckPassword::class)->check($post);

        } catch (ValidateException $e) {

            return $this->outputAjax($e->getError());
        }

        if (!preg_match('/(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[@_%&])[A-Za-z0-9@_%&]{15,20}/',$post['password'])) {
            return $this->outputAjax('密码设置15-20位且必须包含大写字母、小写字母及数字特殊字符包括& @ % _');
        }

        $res = Db::name('admin_user')->where('id', '=', session('admin_auth.id'))->where('password', '=', md5(trim($post['old_password'])))->find();

        if (!$res) {
            return $this->outputAjax('旧密码错误！');
        }

        $update = array(
            'id' => session('admin_auth.id'),
            'password' => md5(trim($post['password']))
        );

        $res = Db::name('admin_user')->update($update);
        if ($res) {
            session('admin_auth', null);
            return $this->outputAjax('修改成功', 0);
        }

        return $this->outputAjax('修改失败');
    }
}